﻿using UnityEngine;
using System.Collections.Generic;
//动量吸收触发器，玩家小球碰到后动量会变为0
public class MetAbsTrigger : MonoBehaviour
{
    public Transform[] AbsPoints;
    public MetumAbsorbObject MetAbsPerfab;

    ObjectPool<MetumAbsorbObject> metumAbsObjPool;
    public float TimeSpan = 1f;

    int cnt;
    float timer;
    List<int> rndValCol;
    bool creatable = false;

    private void Awake()
    {
        timer = TimeSpan;
        rndValCol = new List<int>(AbsPoints.Length);
        cnt = AbsPoints.Length - 1;
        metumAbsObjPool = new ObjectPool<MetumAbsorbObject>(() => Instantiate(MetAbsPerfab));
    }
    private void Update()
    {
        if (creatable)
        {
            timer += Time.deltaTime;
            if (timer >= TimeSpan)
            {
                timer = 0f;
                for (int i = 0; i < AbsPoints.Length; i++)
                    rndValCol.Add(i);
                for (int i = 0; i < cnt; i++)
                {
                    int rnd = Random.Range(0, rndValCol.Count);
                    MetumAbsorbObject obj = metumAbsObjPool.GetObject();
                    obj.SourcePool = metumAbsObjPool;
                    obj.gameObject.SetActive(true);
                    obj.transform.position = AbsPoints[rndValCol[rnd]].position;
                    rndValCol.RemoveAt(rnd);
                }
                rndValCol.Clear();
            }
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {   
        if (collision.transform.CompareTag(Constants.Tag_Player))
        {
            creatable = true;
        }
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.transform.CompareTag(Constants.Tag_Player))
        {
            creatable = false;
        }
    }
}
